import { Context } from 'egg';

export default () => {
    return async function token(ctx: Context, next) {
        const urlArray: string[] = ['/api/assuageGrief/wx/searchAssuageGriefById', '/api/user/searchPicture',
            '/api/user/deletePicture', '/api/user/createPicture','/api/user/wx/updateUserNew',
            '/api/wx/friends/searchFriends', '/api/wx/user/deleteSound','/api/wx/activity/searchActivityListById',
            '/api/user/wx/userReport', '/api/user/wx/shieldUser', '/api/activity/wx/startAndStopWxActivity',
            '/api/user/wx/defriend', '/api/paint/wx/searchPaintValueByUserId',
            '/api/paint/wx/updateUserPaintValue', '/api/user/wx/makeFriends', '/api/wx/praise/dealWithPraise',
            '/api/user/wx/checkRelation', '/api/assuageGrief/wx/searchAssuageGriefAll', '/api/assuageGrief/wx/handleCollection',
            '/api/assuageGrief/wx/searchMyAssuageGrief', '/api/assuageGrief/wx/deleteAssuageGrief', '/api/assuageGrief/wx/searchCollectionAssuageGrief',
            '/api/assuageGrief/wx/searchFriendsAssuageGrief','/api/user/wx/getCloundTokenByUserToken',
            '/api/wx/comment/commentReply', '/api/assuageGrief/wx/createAssuageGrief', '/api/user/wx/editUser',
            '/api/user/wx/editEvaluate', '/api/user/wx/evaluateUser','/api/activity/createWxActivity',
            '/api/wx/activity/activitySignIn', '/api/wx/activity/endingActivity'];
        const token = ctx.headers.usertoken;
        if (token && token.length > 0) {
            const user: any = await ctx.service.userService.searchUserByToken(token);
            if (user.user_id && user.user_id.length > 0) {
                await ctx.service.browseService.computeBrowseTime(user.user_id);
            }
            ctx.request.body.user_id = user.user_id;
        }
        let url = ctx.originalUrl;
        let isNeedToken: boolean = true;
        for (const value of urlArray) {
            if (value === url) {
                const user = await ctx.service.userService.searchUserByToken(token);
                if (user) {
                    await next();
                    isNeedToken = false;
                    break;
                }
            }
        }
        if (!isNeedToken) {
            return;
        } else {
            await next();
        }
    };
};
